<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box{background-color: blueviolet;width: 150px;height: 150px;position: absolute;left: 0;top: 0;z-index: 1;}
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        // 2. 拖拽-事件监听式绑定事件版
        var downE
        var box = document.querySelector('#box')
        box.addEventListener('mousedown',mouse_down)
        function mouse_down(e){
            downE = e || window.event
            document.addEventListener('mousemove',mouse_move)
        }

        function mouse_move(e){
            var moveE = e || window.event
            var l = moveE.pageX - downE.offsetX
            var t = moveE.pageY - downE.offsetY

            if(l<=0){
                box.style.left = 0
            }else if(l > document.documentElement.clientWidth - box.clientWidth){
                box.style.left = document.documentElement.offsetWidth - box.clientWidth +'px'
            }else{
                box.style.left = moveE.pageX - downE.offsetX + 'px' 
            }
            if(t<=0){
                box.style.top = 0
            }else if(t > document.documentElement.clientHeight - box.offsetHeight){
                box.style.top = document.documentElement.clientHeight - box.offsetHeight + 'px'
            }else{
                box.style.top = moveE.pageY - downE.offsetY + 'px'
            }
        }
    </script>
</body>
</html>